const FPS = 30;//帧率
const url="/reco/face/base64Img";
function opencvBiz(){
	    var self = this;
	    var _this = this;
	    this.cameraStarted = false;//摄像头打开、销毁
	    this.detectedFaceAndPause = false;
	    
	    
	    this.src =null,
	    this.dst =null,
	    this.gray =null, 
	    this.cap =null,
	    this.facesRectVector =null, //人脸存放向量
	    this.eyesRectVector =null; 
	    this.faceCascadeClassifier =null; //检测器
	    this.eyeCascadeClassifier =null;
	    
	    this.utils = new Utils('errorMessage');
	    this.video = document.getElementById('videoInput');
	    this.canvasOutput = document.getElementById('canvasOutput');
	    this.canvasContext = canvasOutput.getContext('2d');
	    
	    this.initMat =  function(iniCallback){
	    	
	    	var errDomId=document.getElementById('errorMessage');
	    	if(!errDomId){
	    		 alert("页面内没有找到【errorMessage】的节点");
				return;
	    	}
	    	_this.utils=new Utils('errorMessage');
	    	
	    	 _this.canvasOutput = document.getElementById('canvasOutput');
	    	 if(!_this.canvasOutput){
				   alert("没有找到显示摄像头区域的canvas");
				   return;
			   }
	    	 
			 _this.canvasContext = _this.canvasOutput.getContext('2d');
	    	
			 _this.src = new cv.Mat(_this.video.height, _this.video.width, cv.CV_8UC4); 
			 _this. dst = new cv.Mat(_this.video.height, _this.video.width, cv.CV_8UC1);
			 _this.gray = new cv.Mat();
			 _this. cap = new cv.VideoCapture(_this.video);  
			 
			 _this.facesRectVector = new cv.RectVector();

			 _this.eyesRectVector = new cv.RectVector();

			 _this.faceCascadeClassifier = new cv.CascadeClassifier();

			 _this. eyeCascadeClassifier = new cv.CascadeClassifier();
			 
			 _this.faceCascadeClassifier.load('haarcascade_frontalface_default.xml');
			 _this.eyeCascadeClassifier.load('haarcascade_eye.xml');
			 if(iniCallback){
				 iniCallback();
			 }
		};
		
		 this.processVideo =function(recognizedCallback) { 
			 console.log("processVideo1");
			try { 
				if (_this.cameraStarted==false) { 
					_this.src.delete();
					_this.dst.delete();
					_this.gray.delete();
					_this.facesRectVector.delete();
					_this.eyesRectVector.delete();
					_this.faceCascadeClassifier.delete();
					_this.eyeCascadeClassifier.delete();
					return; 
				} 
				 console.log("processVideo2");
				var begin = Date.now(); 
				 _this.cap.read( _this.src); 
				 _this.src.copyTo( _this.dst);
				 cv.cvtColor( _this.dst,  _this.gray, cv.COLOR_RGBA2GRAY, 0);
				 
				 console.log("processVideo2-detectedFaceAndPause:"+_this.detectedFaceAndPause);
				if(_this.detectedFaceAndPause){
					return;
				}
				var msize = new cv.Size(0.2, 0.2);
				_this.faceCascadeClassifier.detectMultiScale( _this.gray,  _this.facesRectVector, 1.3, 3, 0, msize, msize);
				
				 console.log("processVideo3");
				for (var i = 0; i < _this.facesRectVector.size(); ++i) {
					var face = _this.facesRectVector.get(i);
					var point1 = new cv.Point(face.x, face.y);
					var point2 = new cv.Point(face.x + face.width, face.y + face.height);
		            cv.rectangle( _this.dst, point1, point2, [255, 0, 0, 255]);
		           // cv.imshow('canvasOutput',  _this.dst); 
		            var image = new Image();
					image.src = _this.canvasOutput.toDataURL("image/png");
					var imgdata=image.src ;
					if(imgdata){
						_this.video.style.display="none";
						_this.canvasOutput.style.display="";
						_this.detectedFaceAndPause=true;
						_this.utils.printError('检测到人脸，后台比对中....');
						 $.ajax({
							url:url,
							data: {'faceimg': imgdata},
							dataType: 'json',
							type: 'post',
							success: function(res) {
								console.log(res);
								if(recognizedCallback){
									recognizedCallback(res);
								}
						    
							},
							error: function(xhr, type, errorThrown) {
								alert('网络异常，请稍后再试！');
								_this.detectedFaceAndPause=false;
							}
						}); 
					}
				}
				
				cv.imshow('canvasOutput',  _this.dst); 
				let delay = 1000/FPS - (Date.now() - begin);
				 console.log("processVideo-delay:"+delay);
				setTimeout(_this.processVideo(recognizedCallback), delay); 
			} catch (err) { _this.utils.printError(err); } 
		};
		
		this.startCamera=function(onCameraStartedCallback){
			utils.clearError();
			utils.startCamera('vga', _this.onCameraStarted(onCameraStartedCallback), 'videoInput');
		};
		
		this.stopCamera=function(onCameraStopedCallback){
			utils.stopCamera();
			_this.canvasContext.clearRect(0, 0, _this.canvasOutput.width, _this.canvasOutput.height);
			_this.onCameraStoped(onCameraStopedCallback);
		};
		
		this.resumeDetectFace= function (onResumeDetectFaceCallback,recognizedCallback){
			if(detectedFaceAndPause==false){
				return;
			}
			if(onResumeDetectFaceCallback && (typeof onResumeDetectFaceCallback === "function")){
				onResumeDetectFace;
			}
			//document.getElementById("acq_form").reset();
			_this.utils.printError('人脸检测中.....');
			_this.video.style.display="";
			_this.canvasOutput.style.display="none";
			_this.detectedFaceAndPause=false;
			setTimeout(_this.processVideo(recognizedCallback), 1000);
		};
		
		
		this.onCameraStarted=function(onCameraStartedCallback,recognizedCallback){
			_this.cameraStarted = true;
			_this.initMat();
			setTimeout(_this.processVideo(recognizedCallback), 1000);
			if(onCameraStartedCallback  && (typeof onCameraStartedCallback === "function")){
				onCameraStartedCallback;
			}
			
		};
		this.onCameraStoped=function(onCameraStopedCallback){
			_this.cameraStarted = false;
			_this.canvasContext.clearRect(0, 0, canvasOutput.width, canvasOutput.height);
			if(onCameraStopedCallback&&(typeof onCameraStopedCallback === "function")){
				onCameraStopedCallback;
			}
		};
		this.initAndStart=function(onCameraStartedCallback,recognizedCallback){

			_this.utils.loadOpenCv(() => {
			    var eyeCascadeFile = 'haarcascade_eye.xml';
			    _this.utils.createFileFromUrl(eyeCascadeFile, eyeCascadeFile, () => {
			    	var faceCascadeFile = 'haarcascade_frontalface_default.xml';
			    	_this.utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
			    		_this.utils.clearError();
			    		_this.utils.startCamera('vga', _this.onCameraStarted(onCameraStartedCallback,recognizedCallback), 'videoInput');
			    		_this.utils.printError('系统资源加载完成，人脸检测中');
			        });
			    });
			});
		};
		
}


